const app = angular.module("myApp",['ui.bootstrap', 'ui.bootstrap.treeview2','ui.select2']);
// const app = angular.module("myApp",['ui.bootstrap']);

const treeViewTemplate = `
<tree-view ng-if="graphTree != null && graphTree.g != null" tree-service="graphTree" node-label="text"></tree-view>
`;

app.controller("manageController",['$scope','$compile','$filter','$uibModal',function($scope,$compile,$filter,$uibModal){
    $scope.toJSON = function (val) {
        return angular.toJson(val,true);
    };

    FaultNode.loadFaults();
    $scope.allFaults = FaultNode.faults;
    $scope.faults = [];

    $scope.fault_prop = function(fault){
        // return fault.features.map(f=>f.frequency / f.quantum).reduce((x,y)=>x>y?x:y,0);
        return 1- fault.features.map(f=>f.frequency / f.quantum).map(x=>(1-x)).reduce((x,y)=>x*y,1);
    };
    $scope.toTimeString = function(timestamp){
        return moment(parseInt(timestamp)).format('lll');
    };
    $scope.loadFaults = function(){
        $.get('http://127.0.0.1:8080/faults',function (data) {
            console.info("故障加载为：",data);
            let session = neo4jService.getSession();

            $scope.faults = data.map(fault_features=>{
                let length = fault_features.length;
                let first = fault_features[0];
                let fault = FaultNode.faults.find(f=>f.id==first.fault_id);

                return {
                    fault:fault,
                    features:fault_features,
                    featureNodes:{},
                    checkedReason:[],
                    fault_state:0
                }
            });
            for (let i = 0; i < $scope.faults.length; i++) {
                    Promise.all($scope.faults[i].features.map(fitem=> session.run(`start n=node(${fitem.feature_id}) RETURN n`)))
                        .then(function (features) {
                            for (let k = 0; k < features.length; k++) {
                                let feature = MyNode.fromNeo4jNode(features[k].records[0].get("n"));
                                $scope.faults[i].featureNodes[feature.id] = feature;
                            }
                    }).then(function () {
                        return session.run(`start n=node(${$scope.faults[i].fault.id}) match (n)-[*]->(m:Reason) RETURN m`)
                }).then(function (reasons) {
                        $scope.faults[i].reasons = reasons.records.map(r=>MyNode.fromNeo4jNode(r.get("m")));
                        $.get(`http://127.0.0.1:8080/reason/${$scope.faults[i].fault.id}`,function (data) {
                            $scope.faults[i]["reason_map"] = data;
                            $scope.$apply();
                        });
                    });
            }
        });
    };

    $scope.changeState = function(ft,state){
        ft.fault_state = state;
    };

    $scope.train = function(ft){
        if (ft.checkedReason.length!==0 && confirm("确认该故障成立？")){
            console.info(ft);
            alert("wait");
            $.get('http://127.0.0.1:8080/train/'+ft.fault.id,{
                features:JSON.stringify(ft.features.map(f=>f.feature_id)),
                reasons:JSON.stringify(ft.checkedReason)
            },function (data) {
                console.info("自学习完成：",data);

                $scope.loadFaults();
            });
        }
    };

    $scope.unsure = function(ft){
        if (confirm("确认该故障不成立？")){
            console.info(ft);
            $.get('http://127.0.0.1:8080/clear/'+ft.fault.id,function (data) {
                $scope.loadFaults();
            });
        }
    };

    $scope.submitAll= function () {
        let uncheckedFaults = $scope.faults.filter(ft=>ft.fault_state==1 && ft.checkedReason.length==0);
        if(uncheckedFaults.length>0){
            let msg = uncheckedFaults .map(ft=>ft.fault.name).join(",");
            alert(`以下故障"${msg}"未选择哪些原因成立，请选择后再提交！！！`);
        }else {
            if (confirm("确认对以上内容提交？")){
                Promise.all($scope.faults.filter(ft=>ft.fault_state!=0)
                    .map(ft=> new Promise((resolve,reject)=>{
                        if (ft.fault_state==1){
                            $.get('http://127.0.0.1:8080/train/'+ft.fault.id,{
                                features:JSON.stringify(ft.features.map(f=>f.feature_id)),
                                reasons:JSON.stringify(ft.checkedReason)
                            },function (data) {
                                resolve(data);
                            });
                        } else {
                            $.get('http://127.0.0.1:8080/clear/'+ft.fault.id,function (data) {
                                resolve(data);
                            });
                        }
                    })
                )).then((data)=> {
                    console.info(data);
                    $scope.loadFaults();
                });
            }
        }
    };

    $scope.isSelected = function (ft, reasonId) {
        return ft.checkedReason.indexOf(reasonId)>=0;
    };

    $scope.updateSelection = function ($event, ft, reasonId) {
        let checkbox = $event.target;
        if (checkbox.checked){
            //新选中，添加reasonId 到 ft.checkedReason中
            ft.checkedReason.push(reasonId);
        } else {
            //取消选择，移除
            let idx = ft.checkedReason.indexOf(reasonId);
            ft.checkedReason.splice(idx,1);
        }
    };
}]);
